﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using NxStoreManage;

namespace LengthAiCalculate
{
    public partial class ChangeResult : BaseForm
    {
        public ChangeResult()
        {
            InitializeComponent();
        }

        private AICalculateFrm aICalculateFrm;
        private string mid = "";
        private string length = "";

        public void SetInfo(string mid, string id, string num, string group, AICalculateFrm aICalculateFrm)
        {
            label2.Text = id;
            label4.Text = num;
            label8.Text = group;
            this.mid = mid;
            this.length = group.Split('=')[0];
            this.aICalculateFrm = aICalculateFrm;
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            int.TryParse(label4.Text, out var num);
            int.TryParse(textBox1.Text, out var cNum);
            if (cNum < 0 || cNum > num)
            {
                ShowError("转换的支数必须大于0，小于等于可转换支数！");
                return;
            }
            if (mid == "")
            {
                ShowError("没有选择计划数据！");
                return;
            }
            string cut = label8.Text.Trim().Trim();
            string newGroupID = nxsqlHelper.GetColumnValue("[PM.AiResult]", "id", $"isUserAdd=1 AND mID='{mid}' AND cutGroup='{cut}'");
            List<string> sql = new List<string>();
            if (cNum == num)
            {
                if (newGroupID == "")
                {
                    sql.Add($"INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd) VALUES ('{cut}',{num},{length},0,'ch','{mid}',0,1)");
                }
                else
                {
                    sql.Add($"UPDATE [PM.AiResult] SET num = num + {num} WHERE mID = '{mid}' AND isUserAdd=1 AND cutGroup = '{cut}'");
                }
                sql.Add($"DELETE [PM.AiResult] WHERE ID = {label2.Text}");
            }
            else
            {
                if (newGroupID == "")
                {
                    sql.Add($"INSERT INTO [PM.AiResult] (cutGroup,num,mLength,twoCutNum,opType,mID,isAbandon,isUserAdd) VALUES ('{cut}',{cNum},{length},0,'ch','{mid}',0,1)");
                }
                else
                {
                    sql.Add($"UPDATE [PM.AiResult] SET num = num + {cNum} WHERE mID = '{mid}' AND isUserAdd=1 AND cutGroup = '{cut}'");
                }
                sql.Add($"UPDATE [PM.AiResult] SET num = num - {cNum} WHERE ID = {label2.Text}");
            }
            if (nxsqlHelper.ExcuteSql(sql) > 0)
            {
                aICalculateFrm.Reload();
                ShowMsg("转换成功！");
            }
        }
    }
}